<?php

namespace App\Model;

use Illuminate\Support\Carbon;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletes;

/**
 * App\Model\SaPermission.
 *
 * @property int         $id
 * @property int         $role_id    角色id
 * @property int         $menu_id    菜单id
 * @property Carbon|null $created_at 创建时间
 * @property Carbon|null $updated_at 更新时间
 * @property Carbon|null $deleted_at 删除时间
 *
 * @method static Builder|SaPermission newModelQuery()
 * @method static Builder|SaPermission newQuery()
 * @method static \Illuminate\Database\Query\Builder|SaPermission onlyTrashed()
 * @method static Builder|SaPermission query()
 * @method static Builder|SaPermission whereCreatedAt($value)
 * @method static Builder|SaPermission whereDeletedAt($value)
 * @method static Builder|SaPermission whereId($value)
 * @method static Builder|SaPermission whereMenuId($value)
 * @method static Builder|SaPermission whereRoleId($value)
 * @method static Builder|SaPermission whereUpdatedAt($value)
 * @method static \Illuminate\Database\Query\Builder|SaPermission withTrashed()
 * @method static \Illuminate\Database\Query\Builder|SaPermission withoutTrashed()
 * @mixin \Eloquent
 */
class SaPermission extends BaseModel
{
    use SoftDeletes;
    protected $table = 'sa_permission';

    /**
     * 获取角色用于的菜单权限.
     *
     * @param $roleId
     *
     * @return mixed
     */
    public static function getPermission($roleId)
    {
        $where = ['m.status' => 1, 'p.role_id' => $roleId];
        $field = ['m.id', 'm.parent_id', 'm.name', 'm.alias', 'm.icon'];
        $list  = self::from('sa_permission as p')
                ->leftjoin('sa_menu as m', 'p.menu_id', '=', 'm.id')
                ->where($where)
                ->select($field)
                ->orderBy('m.id')
                ->orderBy('m.sort')
                ->get()
                ->toArray();

        return $list;
    }

    /**
     * 删除角色权限.
     *
     * @param $id
     *
     * @return mixed
     */
    public static function delPermissionByRole($id)
    {
        return self::where(['role_id' => $id])->delete();
    }

    /**
     * 删除菜单权限.
     *
     * @param $id
     *
     * @return mixed
     */
    public static function delPermissionByMenu($id)
    {
        return self::where(['menu_id' => $id])->delete();
    }
}
